import React, { useState } from 'react';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import moment from 'moment';
import planIcon from '@/assets/img/plan_icon.png';
import TRNotification from '#/utils/notification.js';
// @ts-ignore
import { TRCheckboxModal } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import type { ISearchFormData } from '../../type';
import { FREQUENCY_OPTIONS } from '../../dictionary';
import { savePendingH } from '../../service';
import { FrequencySelect, ShowDatePicker, ShowTimePicker } from '../index';
import styles from './index.less';

const TextArea = Input.TextArea;
interface IProps {
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: number) => void;
  setMonthflashKey: (e: number) => void;
  onPress: (data: Record<string, any>) => void;
}

const CreateBatchTodoComponent = (props: IProps) => {
  const { searchFormData, setFlashKey, setMonthflashKey, onPress } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);

  const [form] = Form.useForm();

  const { dealElementOptions, dealElementModalOptions, dealElementDataObj } = searchFormData;

  //  取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    let data = form.getFieldsValue()?.stationList || [];
    data = data.map((item: any) => dealElementDataObj[item]?.[0]?.value);
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const checkedKeys = result?.checkedKeys?.map(
        (item: any) => dealElementDataObj?.[item]?.[0]?.value,
      );
      form.setFieldsValue({ stationList: checkedKeys });
    }
  };

  // 表单提交
  const onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        setLoading(true);
        const { period, periodDate, pendingTime, ...rest } = values;
        const periodStartDate = moment(periodDate[0]).format('YYYY-MM-DD');
        const periodEndDate = moment(periodDate[1]).format('YYYY-MM-DD');
        const pendingStartTime = moment(pendingTime[0]).format('HH:mm:ss');
        const pendingEndTime = moment(pendingTime[1]).format('HH:mm:ss');
        const params = {
          ...rest,
          ...period,
          periodStartDate,
          periodEndDate,
          pendingStartTime,
          pendingEndTime,
          createType: 1,
        };

        const res = await savePendingH(params);
        if (res?.statusCode === HttpCode.SUCCESS) {
          message.info('保存成功！');
          setFlashKey(moment().valueOf());
          setMonthflashKey(moment().valueOf());
          _onCancel();
        } else {
          message.info(res?.message || '保存失败！');
        }
        setLoading(false);
      });
  };

  return (
    <Modal
      width={'50%'}
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>批量创建</span>
        </div>
      }
      onCancel={_onCancel}
      footer={null}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="createBatchTodo"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          <Form.Item
            name="transactionArrange"
            label="待办内容"
            rules={[{ required: true, message: '请填写待办内容' }]}
          >
            <TextArea maxLength={50} placeholder="请填写待办内容" />
          </Form.Item>
          <Form.Item
            name="periodDate"
            label="创建总范围"
            rules={[{ required: true, message: '请选择创建总范围' }]}
          >
            <ShowDatePicker
              type="rangePicker"
              format="YYYY.MM.DD"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item
            name="period"
            label="待办频度"
            rules={[{ required: true, message: '请选择待办频度' }]}
          >
            <FrequencySelect options={FREQUENCY_OPTIONS} />
          </Form.Item>
          <Form.Item
            name="pendingTime"
            label="待办时间"
            rules={[{ required: true, message: '请选择待办时间' }]}
          >
            <ShowTimePicker
              type="rangePicker"
              format="HH:mm"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item
            name="stationList"
            label="相关单元"
            rules={[{ required: true, message: '请选择相关单元' }]}
          >
            <Select
              placeholder={'相关单元'}
              showArrow={true}
              open={false}
              onClick={handelSelectDealElement}
              mode="multiple"
              maxTagTextLength={1}
              maxTagCount={1}
              options={dealElementOptions as any[]}
            />
          </Form.Item>
        </Form>
        <Button type="primary" className={styles.submitBtn} loading={loading} onClick={onSubmit}>
          提交
        </Button>
      </div>
    </Modal>
  );
};

class CreateBatchTodoModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <CreateBatchTodoComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new CreateBatchTodoModal();
